/**
 * Created by liguangsong on 16/8/16.
 */
$(document).ready(function () {
    $(".time").text(moment().format("YYYY年MM月DD日 HH:mm:ss"));
    $.get('/ajax_setShopping/', function(result){
        getBuyList(result);
        getGiftList(result);
        computePrice(result);
        addConfirmButtonClickEvent();
    })
    

});

function computePrice(localData) {
    var total = getPrice(localData, "total");
    $("#total_price").text(total.toFixed(2));
    var savePrice = getPrice(localData, "save") - total;
    $("#econnomize_price").text(savePrice.toFixed(2));
}

function selectGiftTemplate(info, template) {
    var count = info["count"];
    var tr = null;
    if(count > 2 && info["discount"] == true) {
        tr = template.replace(/name/, info["name"]).replace(/type/, info["type"])
            .replace(/count/, parseInt(count / 3));
        return tr;
    }
    return tr;
}


function getBuyList(localData) {
    var template = $("#buy_template").html();
    _.times(localData.length, function (i) {
        var tr = template.replace(/name/, localData[i]["name"]).replace(/type/, localData[i]["type"])
            .replace(/price/, localData[i]["price"]).replace(/unit/, localData[i]["unit"])
            .replace(/count/, localData[i]["count"]).replace(/subtotal/, localData[i]["subtotal"]);
        $("#buy_list_body").append(tr);
    })
}



function getGiftList(localData) {
    var template = $("#gift_template").html();
    _.times(localData.length, function (i) {
        var tr = selectGiftTemplate(localData[i], template);
        $("#gift_list_body").append(tr);
    })
}


function getPrice(localData, type) {
    var total = 0;
    _.times(localData.length, function(index) {
        var beforeSubtotal = localData[index]["subtotal"];
        var markPosition = (type=="save")? beforeSubtotal.lastIndexOf("元"): beforeSubtotal.indexOf("元");
        var pricePosition = (type=="save")? beforeSubtotal.indexOf("：") + 1 : 0;
        var realSubTotal = beforeSubtotal.substring(pricePosition, markPosition);
        total += parseFloat(realSubTotal);

    });
    return total;
}


function addConfirmButtonClickEvent() {
    $("#confirm button").click(function() {
        console.log("clear");
        $.ajax({
            url: '/ajax_setShopping/',
            type: 'AAA',
            success: function(result) {
                console.log(result)
            }
        });

        
        window.location.href = "/goodList/";
    })

}